package com.utc.cards.table.jade.agent.gameAgent;

import jade.core.AID;
import jade.core.behaviours.OneShotBehaviour;
import jade.lang.acl.ACLMessage;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.utc.cards.common.jade.Mapper;
import com.utc.cards.model.HostModel;
import com.utc.cards.model.game.Info;
import com.utc.cards.model.game.InfoType;
import com.utc.cards.model.player.IPlayer;

public class GameGiveTurnBehaviour extends OneShotBehaviour
{

    private static final String CONVERSATION_ID = "info";
    private static final long serialVersionUID = -3316475335163169936L;
    private static Logger log = LoggerFactory.getLogger(GameGiveTurnBehaviour.class);

    private IPlayer player;
    private GameAgent agent;
    private HostModel model;

    public GameGiveTurnBehaviour(GameAgent gameAgent, IPlayer player)
    {
        this.agent = gameAgent;
        this.player = player;
        this.model = agent.getModel();
    }

    @Override
    public void action()
    {
        log.debug("Giving turn to {}", player.getName());
        ACLMessage message = new ACLMessage(ACLMessage.INFORM);
        message.setConversationId(CONVERSATION_ID);
        AID playerAID = model.getPlayersMap().get(player.getName());
        if (playerAID != null)
        {
            message.addReceiver(playerAID);
            Info info = new Info(InfoType.PLAYER_TURN, null);
            try
            {
                message.setContent(Mapper.getObjectMapper().writeValueAsString(info));
                agent.send(message);
                log.debug("Giving turn to {}, message sent", player.getName());
            }
            catch (JsonProcessingException e)
            {
                log.error("Error while mapping Info to String");
                e.printStackTrace();
            }
        }
        else
        {
            log.error("Player not found by name({})", player.getName());
        }

    }

}
